import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

np.random.seed(5)
x_data = np.linspace(-1, 1, 100)

y_data = x_data * 2 + 1.0 + np.random.randn(*x_data.shape) * 0.4

plt.scatter(x_data, y_data)
# plt.plot(x_data, x_data * 2 + 1.0, color="red", linewidth=3)
# plt.show()

x = tf.placeholder("float", name="x")
y = tf.placeholder("float", name="y")

def model(x, w, b):
    return tf.multiply(x, w) + b

w = tf.Variable(1.0, name="w0")
b = tf.Variable(0.0, name="b0")

# 前向计算
pred = model(x, w, b)
# 迭代次数
trains_epochs = 10
# 学习率
learning_rate = 0.05
# 损失函数
loss_function = tf.reduce_mean(tf.square(y - pred))
# 梯度下降算法优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss_function)

sess = tf.Session()

init = tf.global_variables_initializer()
sess.run(init)

for epoch in range(trains_epochs):
    for xs, ys in zip(x_data, y_data):
        _, loss = sess.run([optimizer, loss_function], feed_dict={x: xs, y: ys})
    b0temp = b.eval(session=sess);
    w0temp = w.eval(session=sess);
    plt.plot(x_data, w0temp * x_data + b0temp)
    print('==================================')
    print(b0temp)
    print(w0temp)

x_test = 3.21
pred_redict = sess.run(pred, feed_dict={x: x_test})
print("预测值： %f" % pred_redict)

print("实际值： %f" % (2 * x_test + 1.0))

plt.show()




